﻿using ReflectionMagic;
using System.Windows;
using System.Windows.Media;
using MEdge = Microsoft.Msagl.Core.Layout.Edge;
using MRect = Microsoft.Msagl.Core.Geometry.Rectangle;

namespace Timtopia.DGMLPosterView
{
    public static class GeometryHelper
    {
        private static dynamic geometryConverterType;
        static GeometryHelper()
        {
            var layoutAssembly = typeof(Microsoft.VisualStudio.Diagrams.Layout.WpfToMsaglGeometryConverter).Assembly;
            geometryConverterType = layoutAssembly.GetDynamicType("Microsoft.VisualStudio.Diagrams.Layout.MsaglToWpfGeometryConverter");
        }

        public static Rect ToRect(this MRect r)
        {
            return geometryConverterType.ToRect(r);
        }

        public static Geometry ToGeometry(this MEdge e)
        {
            return geometryConverterType.ToGeometry(e);
        }

        public static Point GetCenter(Rect r)
        {
            return new Point((r.Left + r.Right) / 2, (r.Top + r.Bottom) / 2);
        }

        public static Point[] GetIntersectionPoints(Geometry g1, Geometry g2)
        {
            Geometry og1 = g1.GetWidenedPathGeometry(new Pen(Brushes.Black, 1.0));
            Geometry og2 = g2.GetWidenedPathGeometry(new Pen(Brushes.Black, 1.0));

            CombinedGeometry cg = new CombinedGeometry(GeometryCombineMode.Intersect, og1, og2);

            PathGeometry pg = cg.GetFlattenedPathGeometry();
            Point[] result = new Point[pg.Figures.Count];
            for (int i = 0; i < pg.Figures.Count; i++)
            {
                Rect fig = new PathGeometry(new PathFigure[] { pg.Figures[i] }).Bounds;
                result[i] = new Point(fig.Left + fig.Width / 2.0, fig.Top + fig.Height / 2.0);
            }
            return result;
        }
    }
}
